<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主页面</title>
   <script src="dict/area.js"></script>
    <script src="dict/select.js"></script>
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
    <script>
        $(function () { // DOM 加载完毕默认要执行的函数
            $.ajax({
                url:"citizen/citizens",
                data:"pn=1",
                type:"get",
                success:function (result) {
                    console.log(result)
                    $("#currentPage").text(result.pageNum);
                    $("#pages").text(result.pages);
                    $("#total").text(result.total);
                    // 1、解析并显示员工数据
                    buildUsersTab(result);
                    // 2、解析显示分页信息
                    buildNavTab(result);
                }
            });
        })

        // 获取第几页的数据
        function toPage(pn) {
            console.log("获取第" + pn  + "页数据");
            $.ajax({
                url: "citizen/citizens",
                data: "pn="+pn,
                type:"GET",
                success:function (result) { // 这里面是不是就包括有当前页是第几页
                    // console.log("第" + pn +"页数据",result)
                    // 重新构建数据table
                    buildUsersTab(result);
                    // 重新构建分页条
                    buildNavTab(result);
                    // 更新表格左下角的页码
                    updateCurrentPage(result.pageNum);
                }
            });
        }

        function updateCurrentPage(pageNum) {
            $("#currentPage").text(pageNum);
        }

        // 构建分页条
        function buildNavTab(result) {

            // $("#userstab tbody").empty(); // 这个是去掉表格数据
            $("#pnav").empty();
            console.log(result.hasPreviousPage+ "---",result);
            var ul = $("<ul></ul>").addClass("pagination")
            var firstPageLi = $("<li></li>").append($("<a onclick='toPage(1)'></a>").append("首页").attr("href","#"));
            var prePageLi;
            var nexPageLi;
            if (!result.hasPreviousPage) {
                prePageLi = $("<li></li>").addClass("disabled").append($("<a onclick='toPage("+(result.pageNum-1)+")'></a>").append("&laquo;").attr("href","#")); // 上一页
            } else {
                prePageLi = $("<li></li>").append($("<a onclick='toPage("+(result.pageNum-1)+")'></a>").append("&laquo;").attr("href","#")); // 上一页
            }
            if (!result.hasNextPage) {
                nexPageLi = $("<li></li>").addClass("disabled").append($("<a onclick='toPage("+(result.pageNum+1)+")'></a>").append("&raquo;").attr("href","#")); // 下一页
            } else {
                nexPageLi = $("<li></li>").append($("<a onclick='toPage("+(result.pageNum+1)+")'></a>").append("&raquo;").attr("href","#")); // 下一页
            }

            var lastPageLi = $("<li></li>").append($("<a onclick='toPage("+result.pages+")'></a>").append("尾页").attr("href","#"));
            ul.append(firstPageLi).append(prePageLi);
            // 遍历总的页数
            $.each(result.navigatepageNums,function (index,item){ // item 是分页条上的页码
                // 选中页要成为激活状态active
                var numli;
                if (result.pageNum == item) { // 后台返回的数据显示在表格里的页的数据（有个第几页） == 当前点的页码
                    numli = $("<li></li>").addClass("active").append($("<a onclick='toPage("+item+")'></a>").append(item));
                } else {
                    numli = $("<li></li>").append($("<a onclick='toPage("+item+")'></a>").append(item));
                }
                ul.append(numli);
            });


            ul.append(nexPageLi).append(lastPageLi);
            var nav = $("<nav></nav>").append(ul);
            nav.appendTo("#pnav");
        }
        function buildUsersTab(obj) {
            $("#userstab tbody").empty();
            // 得到obj中的LIST
            var users = obj.list;

            // users：遍历的集合list
            // item：每一条数据
            console.log(users)
            $.each(users, function (index, item) {
                var check=$("<td><input type='checkbox' name='chk' value='"+item.cid+"'></td>")
                var cid = $("<td></td>").append(item.cid);
                var name = $("<td></td>").append(item.name);
                var sex1 = calculateGender(item.card);
                var age1 =calculateAge(item.card);//item.age
                var age = $("<td></td>").append(age1);
                var sex = $("<td></td>").append(sex1);
                var card = $("<td></td>").append(item.card);
                var city = $("<td></td>").append(item.city);
                var dist = $("<td></td>").append(item.dist);
                var address = $("<td></td>").append(item.address);
                var delBtn = $("<td></td>").append($("<button type='button' class='btn btn-danger' onclick='deleteByid("+JSON.stringify(item)+")'>删除</button>"));
                var editBtn = $("<td></td>").append($("<button type='button' class='btn btn-info' data-toggle='modal' data-target='#changemyModal' onclick='changeinfo("+JSON.stringify(item)+")'>编辑</button>"));
                var btnId=$("<td></td>").append(delBtn).append(editBtn);

                $("<tr></tr>")
                    .append(check)
                    .append(cid)
                    .append(name)
                    .append(age)
                    .append(sex)
                    .append(card)
                    .append(city)
                    .append(dist)
                    .append(address)
                    .append(btnId)
                    .appendTo("#userstab tbody");
            });
        }
        function reverseselct(){
            let chks=document.getElementsByName("chk")
            for(var i=0;i<chks.length;i++){
                chks[i].checked=!chks[i].checked
            }
        }
        function delmany(){
            // if(document.getElementsByName("chk")){
            //     alert("请至少选择一行！");
            //     return
            // }
            let chks =document.getElementsByName("chk");
            var temp="";
            for(var i=0;i<chks.length;i++){
                if(chks[i].checked){
                    temp+=chks[i].value+","
                }

            }
            var resultchk=temp.substring(0,temp.length-1)
            var ids = resultchk.split(',').map(Number);
            console.log(ids)
            if(ids.includes(0)){
                    alert("请至少选择一行！");
                    return
                }
            if (confirm("是否确认都删了？"))
            $.ajax({
                url:"citizen/delmany",
                data: JSON.stringify(ids),

                method:"post",
                contentType:"application/json;charset=utf-8",
                success:function (res){
                    if (res=="Y"){
                        alert("删除成功！")
                        location.reload();
                    }else if(res=="N"){
                        alert("删除失败！")
                    }else{
                        alert("请先登录再操作！")
                    }
                    location.reload()
                },

            })

        }
        function searchdata(){
            let value1=document.getElementById("uaccount").value
            let value2=document.getElementById("uage").value
            let value3=document.getElementById("starttime").value
            let value4=document.getElementById("endtime").value
            $.ajax({
                url:"citizen/searct",
                data:{
                    name:value1,
                    age:value2,
                    starttime:value3,
                    endtime:value4
                },
                type:"get",
                contentType:"application/json",


                success:function (item){
                    if(item.length==0){
                        alert("查无此人！");
                        $("#userstab tbody").empty()
                        $(" tfoot").empty();
                        return;
                    }
                    console.log(item)
                    $("#userstab tbody").empty()
                    for(var i=0;i<item.length;i++){
                        var check=$("<td><input type='checkbox' name='chk' value='"+item[i].cid+"'></td>")
                        var cid = $("<td></td>").append(item[i].cid);
                        var name = $("<td></td>").append(item[i].name);
                        var sex1 = calculateGender(item[i].card);
                        var age1 =calculateAge(item[i].card);
                        var age = $("<td></td>").append(age1);
                        var sex = $("<td></td>").append(sex1);
                        var card = $("<td></td>").append(item[i].card);
                        var city = $("<td></td>").append(item[i].city);
                        var dist = $("<td></td>").append(item[i].dist);
                        var address = $("<td></td>").append(item[i].address);
                        var delBtn = $("<td></td>").append($("<button type='button' class='btn btn-danger' onclick='deleteByid("+JSON.stringify(item[i])+")'>删除</button>"));
                        var editBtn = $("<td></td>").append($("<button type='button' class='btn btn-info' data-toggle='modal' data-target='#changemyModal' onclick='changeinfo("+JSON.stringify(item[i])+")'>编辑</button>"));
                        var btnId=$("<td></td>").append(delBtn).append(editBtn);

                        $("<tr></tr>")
                            .append(check)
                            .append(cid)
                            .append(name)
                            .append(age)
                            .append(sex)
                            .append(card)
                            .append(city)
                            .append(dist)
                            .append(address)
                            .append(btnId)
                            .appendTo("#userstab tbody");

                    }

                }


            })

        }
        function deleteByid(item){
            if(confirm("确认删除？")){
                $.ajax({
                    url:"citizen/datadel",
                    data:{
                        cid:item.cid,
                        name:item.name
                    },
                    type:"post",
                    success:function (res){
                        if(res=="Y"){
                            alert("删除成功！")
                        }else if(res=="N"){
                            alert("您只能删除自己添加的！")
                        }else if(res=="same"){
                            alert("您不能删除自己！")
                        }else {
                            alert("请先登录再操作！")
                        }
                        location.reload()

                        // if (res=="Y"){
                        //     alert("删除成功！")
                        //     location.reload();
                        // }else {
                        //     alert("删除失败！")
                        // }
                    }

                })

            }


        }
        function insertdata(){
            var pc=document.getElementById("province1").value+document.getElementById("city1").value
            var age=calculateAge(document.getElementById("card").value);
            var sex=calculateAge(document.getElementById("card").value);
            var town=document.getElementById("town1").value
            console.log(town)
            let datas= {
                age:age,
                sex:sex,
                name:document.getElementById("name").value,
                card:document.getElementById("card").value,
                city:pc,
                dist:town,
                address:document.getElementById("address").value
            }

            $.ajax({
                url:"citizen/insdata",
                data:JSON.stringify(datas),
                type:"post",
                contentType:"application/json;charset=utf-8",

                success:function (res){
                    console.log(res)
                    if (res == "Y") {
                        alert("添加成功")
                        location.reload();
                    } else if(res=="N"){
                        alert("添加失败")
                    }else if(res=="same"){
                        alert("该身份证号已被注册~")
                    }else {
                        alert("请先登录再进行操作！")
                    }
                    location.reload()
                }
            })


        }
        function isValidIDCard(card){
            var regex = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X|x)$/;
            if(!regex.test(card)){
                alert("输入身份证号格式有误！请重新检查并输入~")
            }
        }
        function calculateGender(card){
            const genderDigit = parseInt(card.charAt(16), 10); // 获取第17位数字
            if (isNaN(genderDigit)) {
                return '身份证号码格式错误';
            }

            return genderDigit % 2 === 0 ? '女' : '男';
        }
        function calculateAge(card){
            const birthYear = parseInt(card.substring(6, 10), 10); // 提取出生年份
            const birthMonth = parseInt(card.substring(10, 12), 10); // 提取出生月份
            const birthDay = parseInt(card.substring(12, 14), 10); // 提取出生日

            const birthDate = new Date(birthYear, birthMonth - 1, birthDay); // 注意月份是从0开始的
            const today = new Date();

            let age = today.getFullYear() - birthYear;
            // 如果今天的日期小于出生日期的今年对应日期，则年龄减一
            if (today.getMonth() < birthMonth || (today.getMonth() === birthMonth && today.getDate() < birthDay)) {
                age--;
            }

            return age;
        }
        function openempty(event){
            // document.getElementsByName("name").value.empty();
            // document.getElementsByName("card").value.empty();
            // document.getElementsByName("province").value.empty();
            // document.getElementsByName("city").value.empty();
            // document.getElementsByName("town").value.empty();
            // document.getElementsByName("address").value.empty();
            $(".modal-body #name").val().empty()

        }
        function changeinfo(item){
            document.getElementById("cid").value=item.cid;
            document.getElementById("changename").value=item.name;
            document.getElementById("changeaddress").value=item.address;



        }
        function saveData(){
            if(confirm("是否确认更改？~")){
                var pc=document.getElementById("changeprovince").value+document.getElementById("changecity").value
                var town=document.getElementById("changetown").value
                let user={
                    cid:document.getElementById("cid").value,
                    name:document.getElementById("changename").value,
                    city:pc,
                    dist:town,
                    address:document.getElementById("changeaddress").value,


                }
                console.log(JSON.stringify(user))
                $.ajax({
                    url:"citizen/datasave",
                    data: JSON.stringify(user),
                    method:"POST",
                    contentType:"application/json;charset=utf-8",
                    success:function (res){
                        console.log(res)
                        if(res=="Y"){
                            alert("成功")
                        }else if(res=="N"){
                            alert("失败")
                        }else{
                            alert("请先登录再进行操作！")
                        }
                        location.reload()

                    },

                })

            }


        }
        function Exit(){
            $.ajax({
                url:"citizen/exit",
                method:"POST",
                success:function (res) {

                        alert("退出成功")
                        window.location.href = "./login.html"
                    }

                })
            }
            $(
                function accountShow(){
                    $.ajax({
                        url:"citizen/accountShow",
                        method:"POST",
                        success:function (res) {
                            document.getElementById("accountShow").innerHTML=res
                            if(res==""||res==null){
                                $("#exit").hide();
                            }else {
                                $("#login").hide();
                            }
                        }

                    })
                }

            )

    </script>


</head>
<body>
<div class="pagehead">
    账户：<input type="text" id="uaccount">
    年龄：<input type="text" id="uage">
    日期：<input type="date" id="starttime">--
    <input type="date" id="endtime">
    <button type="button" class="btn btn-danger" onclick="searchdata()">查询</button>
    <button type="button" class="btn btn-danger" onclick="delmany()">批量删除</button>
    <button type="button" class="btn btn-danger " data-toggle="modal" data-target="#myModal">添加</button>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="./login.html"><button type="button" class="btn btn-primary" id="login">登录</button></a>
    <button type="button" class="btn btn-danger" onclick="Exit()" id="exit">退出</button>
    欢迎&nbsp;&nbsp; <span id="accountShow"></span>&nbsp;&nbsp;登录~


</div>
<div class="showtable">
    <table class="table table-bordered" id="userstab">
       <thead>
            <th><input type="checkbox" onclick="reverseselct()"/></th>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>身份证</th>
            <th colspan="2">省市区</th>
            <th>详细地址</th>
            <th>操作</th>
       </thead>
        <tbody>

        </tbody>
        <tfoot>
        <tr>
            <td colspan="3">
                当前<span id="currentPage"></span>页，共有<span id="pages"></span>页，共有<span id="total"></span>条数据

            </td>
            <td colspan="5" align="center">

                <nav aria-label="Page navigation" id="pnav">
                    <ul class="pagination">
                        <li class="disabled">
                            <a href="#" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                        <li><a href="#">1</a></li>
                        <li class="active"><a href="#">2</a></li>
                        <li><a href="#">3</a></li>
                        <li><a href="#">4</a></li>
                        <li><a href="#">5</a></li>
                        <li>
                            <a href="#" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </td>
        </tr>
        </tfoot>
    </table>
</div>
<!-- 添加Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel" onclick="openempty()">添加</h4>
            </div>
            <div class="modal-body">
                姓名：<input type="text" name="name" id="name"><br>
                身份证：<input type="text" id="card" onblur="isValidIDCard(document.getElementById('card').value)"><br>

                <td>
                   省市区： <select name="province" id="province1" class="province">
                        <option value="请选择">请选择</option>
                    </select>
                    <select name="city" id="city1" class="city">
                        <option value="请选择">请选择</option>
                    </select>
                    <select name="town" id="town1" class="town">
                        <option value="请选择">请选择</option>
                    </select><br>
                </td>
                <td>
                    详细地址：<input type="text" name="address" id="address"><br>
                </td>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary"  onclick="insertdata()">提交</button>
            </div>
        </div>
    </div>
</div>
<!--编辑-->
<div class="modal fade" id="changemyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="changemyModalLabel">添加</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="cid">
                姓名：<input type="text" id="changename"><br>
                <td>
                    省市区： <select name="province" id="changeprovince" class="province">
                    <option value="请选择">请选择</option>
                </select>
                    <select name="city" id="changecity" class="city">
                        <option value="请选择">请选择</option>
                    </select>
                    <select name="town" id="changetown" class="town">
                        <option value="请选择">请选择</option>
                    </select><br>
                </td>
                <td>
                    详细地址：<input type="text" id="changeaddress"><br>
                </td>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary"  onclick="saveData()">保存修改</button>
            </div>
        </div>
    </div>
</div>
<script>
    //省市区三级联查
    var province=$(".province")
    var city=$(".city")
    var town=$(".town")
    for(var i=0;i<provinceList.length;i++){
        addEle(province,provinceList[i].name);
    }
    function addEle(ele,value){
        var optionStr="";
        optionStr="<option value="+value+">"+value+"</option>";
        ele.append(optionStr);
    }
    function removeEle(ele){
        ele.find("option").remove();
        var optionStar="<option value="+"请选择"+">"+"请选择"+"</option>";
        ele.append(optionStar);
    }
    var provinceText,cityText,cityItem;
    province.on("change",function(){
        provinceText=$(this).val();
        $.each(provinceList,function(i,item){
            if(provinceText == item.name){
                cityItem=i;
                return cityItem
            }
        });
        removeEle(city);
        removeEle(town);
        $.each(provinceList[cityItem].cityList,function(i,item){
            addEle(city,item.name)
        })
    });
    city.on("change",function(){
        cityText=$(this).val();
        removeEle(town);
        $.each(provinceList,function(i,item){
            if(provinceText == item.name){
                cityItem=i;
                return cityItem
            }
        });
        $.each(provinceList[cityItem].cityList,function(i,item){
            if(cityText == item.name){
                for(var n=0;n<item.areaList.length;n++){
                    addEle(town,item.areaList[n])
                }
            }
        });
    });
</script>
</body>
</html>